package com.tarry.trade.counter.service;

import com.google.errorprone.annotations.Var;
import com.google.gson.Gson;
import com.tarry.trade.counter.cache.CacheType;
import com.tarry.trade.counter.cache.RedisStringCache;
import com.tarry.trade.counter.entity.Account;
import com.tarry.trade.counter.entity.User;
import com.tarry.trade.counter.exception.BusinessException;
import com.tarry.trade.counter.mapper.UserMapper;
import com.tarry.trade.counter.thirdpart.uuid.MyUUID;
import com.tarry.trade.counter.util.GsonUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;

@Service
@Slf4j
public class UserService {

    @Resource
    private UserMapper userMapper;

    public Account login(long uid, String password, String captcha, String captchaId) {
        // 参数校验

        // 缓存校验码是否失效 以及验证码是否正确
        String captchaCache = RedisStringCache.get(captchaId, CacheType.CAPTCHA);
        if (StringUtils.isEmpty(captchaCache)) {
            // 验证码不存在或已过期
            throw new BusinessException("验证码不存在或已过期");
        }
        if (!StringUtils.equalsIgnoreCase(captchaCache, captcha)) {
            // 验证码错误
            throw new BusinessException("验证码错误");
        }

        // 数据库对比用户名、密码
        User user = userMapper.queryAccount(uid, password);
        if (Objects.isNull(user)) {
            // 用户名、密码错误
            throw new BusinessException("用户名、密码错误");
        }
        String token = String.valueOf(MyUUID.getInstance().getUUID());
        Account account = Account.builder().id(user.getId())
                .uid(user.getUid())
                .lastLoginTime(user.getModifyTime())
                .lastLoginDate(user.getModifyDate()).token(token).build();
        // 登录成功，生成token 并写入缓存
        RedisStringCache.cache(token, GsonUtils.toJson(account), CacheType.ACCOUNT);

        // 记录登录时间
        Date date = new Date();
        String loginDate = DateFormatUtils.format(date, DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.getPattern());
        String loginTime = DateFormatUtils.format(date, DateFormatUtils.ISO_8601_EXTENDED_TIME_FORMAT.getPattern());
        userMapper.updateLoginTime(user.getId(), loginDate, loginTime);
        return account;
    }

    /**
     * 交易token是否存在
     * @param token
     * @return
     */

    public boolean accountExistInCache(String token) {
        if (StringUtils.isBlank(token)) {
            return false;
        }
        String account = RedisStringCache.get(token, CacheType.ACCOUNT);
        // token存在，刷新缓存
        if (Objects.nonNull(account)) {
            RedisStringCache.cache(token, account, CacheType.ACCOUNT);
            return true;
        }
        return false;

    }

}
